package api

import (
	"fmt"
	"io/ioutil"
	"path/filepath"
	"strings"

	"gitee.com/zhaokangming/tiny-ticktok/config"
	"gitee.com/zhaokangming/tiny-ticktok/model"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/app"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/errcode"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/auth"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/convert"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/oss"
	"gitee.com/zhaokangming/tiny-ticktok/service"

	"github.com/gin-gonic/gin"
)

// VideoListResponse get video list
type VideoListResponse struct {
	app.Response
	VideoList []model.Video `json:"video_list"`
}

// Publish check token then save upload file to qiniu oss
func Publish(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	title, ok := c.GetPostForm("title")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	data, err := c.FormFile("data")
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	filename := filepath.Base(data.Filename)
	finalName := fmt.Sprintf("%d_%s", claims.ID, filename)
	filenameOnly := strings.TrimSuffix(finalName, filepath.Ext(finalName))
	content, err := data.Open()
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	byteFile, err := ioutil.ReadAll(content)
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	err = oss.Upload(c, byteFile, "video/"+finalName)
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	err = service.CreateVideo(c, claims.ID, model.Video{
		PlayUrl:  config.TikTok.URL + filepath.Join("/video/", finalName),
		CoverUrl: config.TikTok.URL + filepath.Join("/image/", filenameOnly+".jpg"),
		Title:    title,
	})
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	app.WriteResponse(c, nil, nil)
}

// PublishList get video list of target user
func PublishList(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	userID, ok := c.GetQuery("user_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	var targetID int64
	if userID == "0" {
		targetID = claims.ID
	} else {
		targetID = convert.StrTo(userID).MustInt64()
	}

	res, err := service.MGetVideosByUID(c, claims.ID, targetID)
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	app.WriteResponse(c, nil, res)
}
